/*
 * @Author: 肖思汗 
 * @Date: 2020-08-04 23:46:42 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2021-05-09 12:56:44
 */

import globalStore from "src/globalStore";
import ReactMixinComponent from "@ReactMixinComponent";
import React from "react";
import styles from "./DragTest.less";
import dragTestStoroe from "./dragTestStore";

interface Props { }

interface State {
    mousedown: boolean
}

export default class DragTest extends ReactMixinComponent<Props, State> {
    constructor(props: Props) {
        super(props);
    }

    state: State = {
        mousedown: false
    }

    mousedown: boolean = false;

    pointDom?: HTMLSpanElement | null;

    // 修改 mobx 数据管理中心的数据
    move(e: React.MouseEvent) {
        if (this.mousedown) {
            const { currentTarget, pageX, pageY } = e;
            const { top, left } = (currentTarget as HTMLDivElement).getBoundingClientRect();
            // const { unZoom } = globalStore;
            dragTestStoroe.top = pageY - top - 10;
            dragTestStoroe.left = pageX - left - 10;
        }
    }

    componentDidMount() {
        let { mixin_emitter } = this;

        // 使用 mixin_emitter 监听事件时, 组件销毁后 由ReactMixinComponent 统一取消监听
        this.mixin_emitter.on(mixin_emitter.HISTORY_CHANGE, () => { });

        // 监听公共状态的改变自动执行
        this.mixin_autorun(() => {
            const { top, left } = dragTestStoroe;

            if (this.pointDom) {
                Object.assign(this.pointDom.style, {
                    top: `${top}px`,
                    left: `${left}px`,
                })
            }

        });
    }

    render() {

        const { mousedown } = this.state;

        return (
            <div
                className={styles.box}
                onMouseMove={(e) => this.move(e)}
                onMouseUp={() => {
                    this.setState({ mousedown: false });
                    this.mousedown = false;
                }}
            >
                <span
                    className={styles.point}
                    ref={dom => this.pointDom = dom}
                    style={{
                        pointerEvents: mousedown ? "none" : "unset"
                    }}
                    onMouseDown={() => {
                        this.setState({ mousedown: true });
                        this.mousedown = true;
                    }}
                />
            </div >
        );
    }

}